var app = getApp();
import {
  api,
  util,
  dialog,
  forms,
  storage
} from '../../../js/util'
import {
  router
} from '../../../js/router';
import {
  fastorder,
  order,
  cart
} from "../../../js/modules/order.js"
import {
  detail,
  mall,
  list,
  scant
} from "../../../js/modules/mall.js";
import {
  activities
} from '../../../js/modules/market';
import authorize from '../../../js/modules/authorize.js'
import {
  GoodsNumCache
} from '../../../js/modules/propertycache.js'
import { alert, isEmpty } from '../../../js/newUtil';
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  behaviors: [componentBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    item: {
      type: Object,
      value: {}
    },
    list:{
      type: Object,
      value: {}
    },
    quantityDigits: {
      type: Number,
      value: 0
    },
    isScanty: {
      type: Boolean,
      value: false
    },
    picX: {
      type: Number,
      value: 200
    },
    picY: {
      type: Number,
      value: 200
    },
    idx:{
      type:Number,
      value:0,
    },
    primaryKey: {
      type: String,
      value: ""
    },
    GoodsUnitDisplayMode:{
      type:Number,
      value:0
    },
    index:{
      type:Number,
      value:0
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    iptType:false,
    max: 999999,
    sMax: 999999,
    min: 0,
  },

  observers: {
    'item,GoodsUnitDisplayMode,list' () {
      this.calculateLimit()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 直接加入购物车
     */
    onDirectCart: function(e) {
      if (!authorize.isLogin('store')) {
        util.tips("你还未登录");
        authorize.redirect("store");
        return;
      }
      var that = this;
      var idx = this.data.idx, idxs = that.data.index, primaryKey = this.data.primaryKey, quantityDigits = this.data.quantityDigits,GoodsUnitDisplayMode = that.data.GoodsUnitDisplayMode;
      var product = this.data.item;
      var auxRate = product.Translated || product.Radix;
      var auxUnit = product.AuxUnit || product.DefaultUnit;
      var num = e.detail.value || 0, pre_num = product.CartCount;
      product.GoodsUnitDisplayMode = GoodsUnitDisplayMode;
      if(GoodsUnitDisplayMode == 1){
        product.idxs = idxs;
        product.AuxiliaryUnits[idxs].Qty = num;
        product.CartCount = 0;
        auxRate = product.AuxiliaryUnits[idxs].Translated;
        auxUnit = product.AuxiliaryUnits[idxs].Name;
        if(product.isPanic){
          product.PanicGoods.map((p)=>{
            let price_obj = detail.parseRule(p.UnitPrices, (product.AuxiliaryUnits[idxs].Translated || product.Radix),num == 0?1:num,true);
            if (price_obj.has) {
              //如果价格没有变化时，则不给数据源重新绑定值
              if (product.AuxiliaryUnits[idxs].price != price_obj.price || (product.AuxiliaryUnits[idxs].price || 0) != (price_obj.integral || 0)) {
                product.AuxiliaryUnits[idxs].integral = price_obj.integral;
                product.AuxiliaryUnits[idxs].price = price_obj.price;
              }
            }
          })
        }else{
          let price_obj = detail.parseRule(product.UnitPrices, (product.AuxiliaryUnits[idxs].Translated || product.Radix),num == 0?1:num,true);
          if (price_obj.has) {
            //如果价格没有变化时，则不给数据源重新绑定值
            if (product.AuxiliaryUnits[idxs].price != price_obj.price || (product.AuxiliaryUnits[idxs].price || 0) != (price_obj.integral || 0)) {
              product.AuxiliaryUnits[idxs].integral = price_obj.integral;
              product.AuxiliaryUnits[idxs].price = price_obj.price;
            }
          }
        }
      }else{
        if (!product.ZIndex) {
          product.ZIndex = 0
        }
        if(product.ZIndex > -1){
          product.AuxiliaryUnits[product.ZIndex].Qty = num;
        }
        product.CartCount = num;
        let price_obj = detail.parseRule(product.UnitPrices, (product.Translated || product.Radix),num,true);
        if (price_obj.has) {
          //如果价格没有变化时，则不给数据源重新绑定值
          if (product.SalesPrice != price_obj.price || (product.SalesIntegral || 0) != (price_obj.integral || 0)) {
            product.SalesIntegral = price_obj.integral;
            product.SalesPrice = price_obj.price;
          }
        }
      }
      let totalUnitQuantity = 0 // 全部的规格数量
      for(var i=0;i<product.AuxiliaryUnits.length;i++){
        var item = product.AuxiliaryUnits[i];
        var otherAuxiliaryUnits = product.AuxiliaryUnits.filter(unit=>{return unit.Translated != item.Translated});
        var otherUnitQuantity = 0;
        if (otherAuxiliaryUnits&&otherAuxiliaryUnits.length>0) {
            otherAuxiliaryUnits.map((child, idx) => {
                if (child.Qty!=undefined&&child.Qty>0) {
                    otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
                }
            });
        }
        item.BuyLowerLimit = product.SBuyLowerLimit > 0 && product.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", product.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
        item.BuyUpperLimit = product.SBuyUpperLimit > 0 && product.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", product.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
        item.Stock = product.SStock > 0 && product.SStock > otherUnitQuantity ? util.keepDecimal("ceil", product.SStock - otherUnitQuantity, quantityDigits) : 0;
        if(GoodsUnitDisplayMode == 1){
          product.CartCount += item.Qty * item.Translated;
        }
        totalUnitQuantity += (item.Qty || 0) * (item.Translated || 1)
      }
      that.alertMessage(totalUnitQuantity)
      that.triggerEvent("onAddCartCompleted", { product: product, idx: idx, primaryKey: primaryKey });
      var goodsXml = `<Goods>
          <FkFlag>2</FkFlag>
          <FkId>${product.FKId||app.dns.proprietorId}</FkId>
          <ProductId>${product.ProductId}</ProductId>
          <GoodsId>${product.GoodsId||product.ProductGoodsId}</GoodsId>
          <SpecValue><![CDATA[${product.SpecValue}]]></SpecValue>
          <DiscountId>${product.DiscountId || 0}</DiscountId>
          <DiscountType>${product.DiscountType || 0}</DiscountType>
          <Quantity>${num * auxRate}</Quantity>
          <AuxQty>${num}</AuxQty>
          <AuxRate>${auxRate}</AuxRate>
          <AuxUnit>${auxUnit}</AuxUnit>
          </Goods>`;
      cart.batchAddCart(goodsXml,function(status, content){
        if(status){
          if (num > 0) {
            GoodsNumCache.add(product.ProductId, product.GoodsId || product.ProductGoodsId, num, auxRate);
          } else {
            GoodsNumCache.del(product.GoodsId || product.ProductGoodsId);
          }
        }else{
          util.tips(content||"加入购物车失败");
          product.CartCount = pre_num;
          that.triggerEvent("onAddCartCompleted", { product: product, idx: idx, primaryKey: primaryKey });
        }
      });
    },
    onShowGoodsModal(e) {
      if (!authorize.isLogin('store')) {
        util.tips("你还未登录");
        authorize.redirect("store");
        return;
      }
      let that=this;
      if (that.data.init_timeout) {
        clearTimeout(that.data.init_timeout);
      }
      this.data.init_timeout = setTimeout(() => {
      var that = this;
      var idx = this.data.idx, primaryKey = this.data.primaryKey;
      var product = this.data.item;
      var num = e.detail.value;
        that.triggerEvent("onShowGoodsModal",{ product:product,idx: idx, primaryKey: primaryKey });
      },300);
    },
    /**
     * 计算输入的最大最小值
     */
    calculateLimit() {
      let {
        item,
        GoodsUnitDisplayMode,
        list
      } = this.data
      let PanicBuy = item.PanicBuy || []
      PanicBuy = PanicBuy[0] || {}
      let type = PanicBuy.type || -1
      let ExceedLimitOriginalPriceBuy = PanicBuy.ExceedLimitOriginalPriceBuy || 0
      let marketGoods = PanicBuy.marketGoods || PanicBuy.PanicGoods || [] // 特价商品列表
      let marketIds = marketGoods.map(i => parseInt(i.GoodsId)) // 特价商品Id
      let GoodsId = parseInt(item.GoodsId || item.ProductGoodsId) // 当前商品的GoodsId,
      let isPanicBuyGoods = marketIds.includes(GoodsId) // 是否是特价商品（多规格商品可能只有部分是特价，需要再次判断）
      let max = 999999
      let sMax = 999999 // 原最大值（特价商品限购最大数量）
      let min = 0
      let data = {}
      if (GoodsUnitDisplayMode == 1 && item.IsSingle == 1 && item.AuxiliaryUnits.length > 1) {
        data = list
      } else {
        data = item
      }
      if (data.ZeroStockBuy > 0 || (data.Stock >= data.BuyUpperLimit && item.SBuyUpperLimit > 0)) {
        if (type == 3 && ExceedLimitOriginalPriceBuy == 1 && isPanicBuyGoods) {
          // 当开启了特价商品超过数量原价购买
          if (data.ZeroStockBuy > 0) {
            max = 999999
          } else {
            if (data.Stock > 0) {
              max = data.Stock
            } else {
              max = 0
            }
          }
          // 原最大值为BuyUpperLimit
          if (data.BuyUpperLimit > 0) {
            sMax = data.BuyUpperLimit
          } else {
            sMax = 0
          }
        } else {
          if (data.BuyUpperLimit > 0) {
            max = data.BuyUpperLimit
          } else {
            max = 0
          }
          sMax = max
        }
      } else {
        if (data.Stock > 0) {
          max = data.Stock
        } else {
          max = 0
        }
        sMax = max
      }
      min = data.BuyLowerLimit || 0
      this.setData({
        max,
        min,
        sMax
      })
    },
    /**
     * 提示用户超出特价的数量
     * @param {*} totalUnitQuantity 商品多个单位的总数量（基础单位）
     */
    alertMessage(totalUnitQuantity = 0) {
      let {
        item,
        sMax
      } = this.data
      let PanicBuy = item.PanicBuy || []
      PanicBuy = PanicBuy[0] || {}
      let type = PanicBuy.type || -1
      let ExceedLimitOriginalPriceBuy = PanicBuy.ExceedLimitOriginalPriceBuy || 0
      let marketGoods = PanicBuy.marketGoods || []
      if (type != 3 || ExceedLimitOriginalPriceBuy != 1) {
        return
      }
      // 限定了最大值才提示
      if (item.SBuyUpperLimit > 0) {
        let good = {}
        for (let i = 0; i < marketGoods.length; i++) {
          if (marketGoods[i].ProductId == item.ProductId && marketGoods[i].GoodsId == item.ProductGoodsId) {
            good = marketGoods[i]
          }
        }
        let max = 999999
        let unit = ''
        if (!isEmpty(good)) {
          if (good.MaxQuantity == 0 && good.Stock > 0) {
            max = good.Stock
          } else {
            max = good.MaxQuantity
          }
          unit = item.Unit || ''
        } else {
          max = sMax
          unit = item.Unit || ''
        }
        if (totalUnitQuantity > max) {
          alert(`限优惠${max || ''}${unit || ''},超出将以原售价加购`)
        }
      }
    }
  }
})